Changing comments layout preparing for generated documentation with Phpdocumentor
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 # $Id$
3 /**
4 * This file deals with MySQL interface functions
5 * and query specifics/optimisations
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 define( 'LIST_COMMA', 0 );
14 define( 'LIST_AND', 1 );
15 define( 'LIST_SET', 2 );
16
17 # Number of times to re-try an operation in case of deadlock
18 define( 'DEADLOCK_TRIES', 4 );
19 # Minimum time to wait before retry, in microseconds
20 define( 'DEADLOCK_DELAY_MIN', 500000 );
21 # Maximum time to wait before retry
22 define( 'DEADLOCK_DELAY_MAX', 1500000 );
23
24 /**
25 * Database abstraction object
26 * @category database
27 */
28 class Database {
29
30 #------------------------------------------------------------------------------
31 # Variables
32 #------------------------------------------------------------------------------
33 /* private */ var $mLastQuery = '';
34
35 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
36 /* private */ var $mOut, $mOpened = false;
37
38 /* private */ var $mFailFunction;
39 /* private */ var $mTablePrefix;
40 /* private */ var $mFlags;
41 /* private */ var $mTrxLevel = 0;
42
43 #------------------------------------------------------------------------------
44 # Accessors
45 #------------------------------------------------------------------------------
46 # These optionally set a variable and return the previous state
47
48 # Fail function, takes a Database as a parameter
49 # Set to false for default, 1 for ignore errors
50 function failFunction( $function = NULL ) {
51 return wfSetVar( $this->mFailFunction, $function );
52 }
53
54 # Output page, used for reporting errors
55 # FALSE means discard output
56 function &setOutputPage( &$out ) {
57 $this->mOut =& $out;
58 }
59
60 # Boolean, controls output of large amounts of debug information
61 function debug( $debug = NULL ) {
62 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
63 }
64
65 # Turns buffering of SQL result sets on (true) or off (false). Default is
66 # "on" and it should not be changed without good reasons.
67 function bufferResults( $buffer = NULL ) {
68 if ( is_null( $buffer ) ) {
69 return !(bool)( $this->mFlags & DBO_NOBUFFER );
70 } else {
71 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
72 }
73 }
74
75 # Turns on (false) or off (true) the automatic generation and sending
76 # of a "we're sorry, but there has been a database error" page on
77 # database errors. Default is on (false). When turned off, the
78 # code should use wfLastErrno() and wfLastError() to handle the
79 # situation as appropriate.
80 function ignoreErrors( $ignoreErrors = NULL ) {
81 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
82 }
83
84 # The current depth of nested transactions
85 function trxLevel( $level = NULL ) {
86 return wfSetVar( $this->mTrxLevel, $level );
87 }
88
89 # Get functions
90
91 function lastQuery() { return $this->mLastQuery; }
92 function isOpen() { return $this->mOpened; }
93
94 #------------------------------------------------------------------------------
95 # Other functions
96 #------------------------------------------------------------------------------
97
98 function Database( $server = false, $user = false, $password = false, $dbName = false,
99 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
100 {
101 global $wgOut, $wgDBprefix, $wgCommandLineMode;
102 # Can't get a reference if it hasn't been set yet
103 if ( !isset( $wgOut ) ) {
104 $wgOut = NULL;
105 }
106 $this->mOut =& $wgOut;
107
108 $this->mFailFunction = $failFunction;
109 $this->mFlags = $flags;
110
111 if ( $this->mFlags & DBO_DEFAULT ) {
112 if ( $wgCommandLineMode ) {
113 $this->mFlags &= ~DBO_TRX;
114 } else {
115 $this->mFlags |= DBO_TRX;
116 }
117 }
118
119 if ( $tablePrefix == 'get from global' ) {
120 $this->mTablePrefix = $wgDBprefix;
121 } else {
122 $this->mTablePrefix = $tablePrefix;
123 }
124
125 if ( $server ) {
126 $this->open( $server, $user, $password, $dbName );
127 }
128 }
129
130 /* static */ function newFromParams( $server, $user, $password, $dbName,
131 $failFunction = false, $flags = 0 )
132 {
133 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
134 }
135
136 # Usually aborts on failure
137 # If the failFunction is set to a non-zero integer, returns success
138 function open( $server, $user, $password, $dbName )
139 {
140 # Test for missing mysql.so
141 # Otherwise we get a suppressed fatal error, which is very hard to track down
142 if ( !function_exists( 'mysql_connect' ) ) {
143 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
144 }
145
146 $this->close();
147 $this->mServer = $server;
148 $this->mUser = $user;
149 $this->mPassword = $password;
150 $this->mDBname = $dbName;
151
152 $success = false;
153
154 @/**/$this->mConn = mysql_connect( $server, $user, $password );
155 if ( $dbName != '' ) {
156 if ( $this->mConn !== false ) {
157 $success = @/**/mysql_select_db( $dbName, $this->mConn );
158 if ( !$success ) {
159 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
160 }
161 } else {
162 wfDebug( "DB connection error\n" );
163 wfDebug( "Server: $server, User: $user, Password: " .
164 substr( $password, 0, 3 ) . "...\n" );
165 $success = false;
166 }
167 } else {
168 # Delay USE query
169 $success = !!$this->mConn;
170 }
171
172 if ( !$success ) {
173 $this->reportConnectionError();
174 $this->close();
175 }
176 $this->mOpened = $success;
177 return $success;
178 }
179
180 # Closes a database connection, if it is open
181 # Commits any open transactions
182 # Returns success, true if already closed
183 function close()
184 {
185 $this->mOpened = false;
186 if ( $this->mConn ) {
187 if ( $this->trxLevel() ) {
188 $this->immediateCommit();
189 }
190 return mysql_close( $this->mConn );
191 } else {
192 return true;
193 }
194 }
195
196 /* private */ function reportConnectionError( $msg = '')
197 {
198 if ( $this->mFailFunction ) {
199 if ( !is_int( $this->mFailFunction ) ) {
200 $ff = $this->mFailFunction;
201 $ff( $this, mysql_error() );
202 }
203 } else {
204 wfEmergencyAbort( $this, mysql_error() );
205 }
206 }
207
208 # Usually aborts on failure
209 # If errors are explicitly ignored, returns success
210 function query( $sql, $fname = '', $tempIgnore = false )
211 {
212 global $wgProfiling, $wgCommandLineMode;
213
214 if ( $wgProfiling ) {
215 # generalizeSQL will probably cut down the query to reasonable
216 # logging size most of the time. The substr is really just a sanity check.
217 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
218 wfProfileIn( $profName );
219 }
220
221 $this->mLastQuery = $sql;
222
223 if ( $this->debug() ) {
224 $sqlx = substr( $sql, 0, 500 );
225 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
226 wfDebug( "SQL: $sqlx\n" );
227 }
228 # Add a comment for easy SHOW PROCESSLIST interpretation
229 if ( $fname ) {
230 $commentedSql = "/* $fname */ $sql";
231 } else {
232 $commentedSql = $sql;
233 }
234
235 # If DBO_TRX is set, start a transaction
236 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
237 $this->begin();
238 }
239
240 # Do the query and handle errors
241 $ret = $this->doQuery( $commentedSql );
242 if ( false === $ret ) {
243 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
244 }
245
246 if ( $wgProfiling ) {
247 wfProfileOut( $profName );
248 }
249 return $ret;
250 }
251
252 # The DBMS-dependent part of query()
253 function doQuery( $sql ) {
254 if( $this->bufferResults() ) {
255 $ret = mysql_query( $sql, $this->mConn );
256 } else {
257 $ret = mysql_unbuffered_query( $sql, $this->mConn );
258 }
259 return $ret;
260 }
261
262 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
263 global $wgCommandLineMode, $wgFullyInitialised;
264 # Ignore errors during error handling to avoid infinite recursion
265 $ignore = $this->ignoreErrors( true );
266
267 if( $ignore || $tempIgnore ) {
268 wfDebug("SQL ERROR (ignored): " . $error . "\n");
269 } else {
270 $sql1line = str_replace( "\n", "\\n", $sql );
271 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
272 wfDebug("SQL ERROR: " . $error . "\n");
273 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
274 $message = "A database error has occurred\n" .
275 "Query: $sql\n" .
276 "Function: $fname\n" .
277 "Error: $errno $error\n";
278 if ( !$wgCommandLineMode ) {
279 $message = nl2br( $message );
280 }
281 wfDebugDieBacktrace( $message );
282 } else {
283 // this calls wfAbruptExit()
284 $this->mOut->databaseError( $fname, $sql, $error, $errno );
285 }
286 }
287 $this->ignoreErrors( $ignore );
288 }
289
290 function freeResult( $res ) {
291 if ( !@/**/mysql_free_result( $res ) ) {
292 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
293 }
294 }
295 function fetchObject( $res ) {
296 @/**/$row = mysql_fetch_object( $res );
297 # FIXME: HACK HACK HACK HACK debug
298 if( mysql_errno() ) {
299 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
300 }
301 return $row;
302 }
303
304 function fetchRow( $res ) {
305 @/**/$row = mysql_fetch_array( $res );
306 if (mysql_errno() ) {
307 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
308 }
309 return $row;
310 }
311
312 function numRows( $res ) {
313 @/**/$n = mysql_num_rows( $res );
314 if( mysql_errno() ) {
315 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
316 }
317 return $n;
318 }
319 function numFields( $res ) { return mysql_num_fields( $res ); }
320 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
321 function insertId() { return mysql_insert_id( $this->mConn ); }
322 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
323 function lastErrno() { return mysql_errno(); }
324 function lastError() { return mysql_error(); }
325 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
326
327 # Simple UPDATE wrapper
328 # Usually aborts on failure
329 # If errors are explicitly ignored, returns success
330 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
331 {
332 $table = $this->tableName( $table );
333 $sql = "UPDATE $table SET $var = '" .
334 $this->strencode( $value ) . "' WHERE ($cond)";
335 return !!$this->query( $sql, DB_MASTER, $fname );
336 }
337
338 function getField( $table, $var, $cond='', $fname = 'Database::getField', $options = array() ) {
339 return $this->selectField( $table, $var, $cond, $fname = 'Database::get', $options = array() );
340 }
341
342 # Simple SELECT wrapper, returns a single field, input must be encoded
343 # Usually aborts on failure
344 # If errors are explicitly ignored, returns FALSE on failure
345 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() )
346 {
347 if ( !is_array( $options ) ) {
348 $options = array( $options );
349 }
350 $options['LIMIT'] = 1;
351
352 $res = $this->select( $table, $var, $cond, $fname, $options );
353 if ( $res === false || !$this->numRows( $res ) ) {
354 return false;
355 }
356 $row = $this->fetchRow( $res );
357 if ( $row !== false ) {
358 $this->freeResult( $res );
359 return $row[0];
360 } else {
361 return false;
362 }
363 }
364
365 # Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the query
366 function makeSelectOptions( $options ) {
367 if ( !is_array( $options ) ) {
368 $options = array( $options );
369 }
370
371 $tailOpts = '';
372
373 if ( isset( $options['ORDER BY'] ) ) {
374 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
375 }
376 if ( isset( $options['LIMIT'] ) ) {
377 $tailOpts .= " LIMIT {$options['LIMIT']}";
378 }
379
380 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
381 $tailOpts .= ' FOR UPDATE';
382 }
383
384 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
385 $tailOpts .= ' LOCK IN SHARE MODE';
386 }
387
388 if ( isset( $options['USE INDEX'] ) ) {
389 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
390 } else {
391 $useIndex = '';
392 }
393 return array( $useIndex, $tailOpts );
394 }
395
396 # SELECT wrapper
397 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
398 {
399 if ( is_array( $vars ) ) {
400 $vars = implode( ',', $vars );
401 }
402 if ($table!='')
403 $from = ' FROM ' .$this->tableName( $table );
404 else
405 $from = '';
406
407 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
408
409 if ( $conds !== false && $conds != '' ) {
410 if ( is_array( $conds ) ) {
411 $conds = $this->makeList( $conds, LIST_AND );
412 }
413 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
414 } else {
415 $sql = "SELECT $vars $from $useIndex $tailOpts";
416 }
417 return $this->query( $sql, $fname );
418 }
419
420 function getArray( $table, $vars, $conds, $fname = 'Database::getArray', $options = array() ) {
421 return $this->selectRow( $table, $vars, $conds, $fname, $options );
422 }
423
424 # Single row SELECT wrapper
425 # Aborts or returns FALSE on error
426 #
427 # $vars: the selected variables
428 # $conds: a condition map, terms are ANDed together.
429 # Items with numeric keys are taken to be literal conditions
430 # Takes an array of selected variables, and a condition map, which is ANDed
431 # e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
432 # would return an object where $obj->cur_id is the ID of the Astronomy article
433 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
434 $options['LIMIT'] = 1;
435 $res = $this->select( $table, $vars, $conds, $fname, $options );
436 if ( $res === false || !$this->numRows( $res ) ) {
437 return false;
438 }
439 $obj = $this->fetchObject( $res );
440 $this->freeResult( $res );
441 return $obj;
442
443 }
444
445 # Removes most variables from an SQL query and replaces them with X or N for numbers.
446 # It's only slightly flawed. Don't use for anything important.
447 /* static */ function generalizeSQL( $sql )
448 {
449 # This does the same as the regexp below would do, but in such a way
450 # as to avoid crashing php on some large strings.
451 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
452
453 $sql = str_replace ( "\\\\", '', $sql);
454 $sql = str_replace ( "\\'", '', $sql);
455 $sql = str_replace ( "\\\"", '', $sql);
456 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
457 $sql = preg_replace ('/".*"/s', "'X'", $sql);
458
459 # All newlines, tabs, etc replaced by single space
460 $sql = preg_replace ( "/\s+/", ' ', $sql);
461
462 # All numbers => N
463 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
464
465 return $sql;
466 }
467
468 # Determines whether a field exists in a table
469 # Usually aborts on failure
470 # If errors are explicitly ignored, returns NULL on failure
471 function fieldExists( $table, $field, $fname = 'Database::fieldExists' )
472 {
473 $table = $this->tableName( $table );
474 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
475 if ( !$res ) {
476 return NULL;
477 }
478
479 $found = false;
480
481 while ( $row = $this->fetchObject( $res ) ) {
482 if ( $row->Field == $field ) {
483 $found = true;
484 break;
485 }
486 }
487 return $found;
488 }
489
490 # Determines whether an index exists
491 # Usually aborts on failure
492 # If errors are explicitly ignored, returns NULL on failure
493 function indexExists( $table, $index, $fname = 'Database::indexExists' )
494 {
495 $info = $this->indexInfo( $table, $index, $fname );
496 if ( is_null( $info ) ) {
497 return NULL;
498 } else {
499 return $info !== false;
500 }
501 }
502
503 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
504 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
505 # SHOW INDEX should work for 3.x and up:
506 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
507 $table = $this->tableName( $table );
508 $sql = 'SHOW INDEX FROM '.$table;
509 $res = $this->query( $sql, $fname );
510 if ( !$res ) {
511 return NULL;
512 }
513
514 while ( $row = $this->fetchObject( $res ) ) {
515 if ( $row->Key_name == $index ) {
516 return $row;
517 }
518 }
519 return false;
520 }
521 function tableExists( $table )
522 {
523 $table = $this->tableName( $table );
524 $old = $this->ignoreErrors( true );
525 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
526 $this->ignoreErrors( $old );
527 if( $res ) {
528 $this->freeResult( $res );
529 return true;
530 } else {
531 return false;
532 }
533 }
534
535 function fieldInfo( $table, $field )
536 {
537 $table = $this->tableName( $table );
538 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
539 $n = mysql_num_fields( $res );
540 for( $i = 0; $i < $n; $i++ ) {
541 $meta = mysql_fetch_field( $res, $i );
542 if( $field == $meta->name ) {
543 return $meta;
544 }
545 }
546 return false;
547 }
548
549 function fieldType( $res, $index ) {
550 return mysql_field_type( $res, $index );
551 }
552
553 function indexUnique( $table, $index ) {
554 $indexInfo = $this->indexInfo( $table, $index );
555 if ( !$indexInfo ) {
556 return NULL;
557 }
558 return !$indexInfo->Non_unique;
559 }
560
561 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
562 return $this->insert( $table, $a, $fname = 'Database::insertArray', $options = array() );
563 }
564
565 # INSERT wrapper, inserts an array into a table
566 #
567 # $a may be a single associative array, or an array of these with numeric keys, for
568 # multi-row insert.
569 #
570 # Usually aborts on failure
571 # If errors are explicitly ignored, returns success
572 function insert( $table, $a, $fname = 'Database::insert', $options = array() )
573 {
574 # No rows to insert, easy just return now
575 if ( !count( $a ) ) {
576 return true;
577 }
578
579 $table = $this->tableName( $table );
580 if ( !is_array( $options ) ) {
581 $options = array( $options );
582 }
583 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
584 $multi = true;
585 $keys = array_keys( $a[0] );
586 } else {
587 $multi = false;
588 $keys = array_keys( $a );
589 }
590
591 $sql = 'INSERT ' . implode( ' ', $options ) .
592 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
593
594 if ( $multi ) {
595 $first = true;
596 foreach ( $a as $row ) {
597 if ( $first ) {
598 $first = false;
599 } else {
600 $sql .= ',';
601 }
602 $sql .= '(' . $this->makeList( $row ) . ')';
603 }
604 } else {
605 $sql .= '(' . $this->makeList( $a ) . ')';
606 }
607 return !!$this->query( $sql, $fname );
608 }
609
610 function updateArray( $table, $values, $conds, $fname = 'Database::updateArray' ) {
611 return $this->update( $table, $values, $conds, $fname );
612 }
613
614 # UPDATE wrapper, takes a condition array and a SET array
615 function update( $table, $values, $conds, $fname = 'Database::update' )
616 {
617 $table = $this->tableName( $table );
618 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
619 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
620 $this->query( $sql, $fname );
621 }
622
623 # Makes a wfStrencoded list from an array
624 # $mode: LIST_COMMA - comma separated, no field names
625 # LIST_AND - ANDed WHERE clause (without the WHERE)
626 # LIST_SET - comma separated with field names, like a SET clause
627 function makeList( $a, $mode = LIST_COMMA )
628 {
629 if ( !is_array( $a ) ) {
630 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
631 }
632
633 $first = true;
634 $list = '';
635 foreach ( $a as $field => $value ) {
636 if ( !$first ) {
637 if ( $mode == LIST_AND ) {
638 $list .= ' AND ';
639 } else {
640 $list .= ',';
641 }
642 } else {
643 $first = false;
644 }
645 if ( $mode == LIST_AND && is_numeric( $field ) ) {
646 $list .= "($value)";
647 } else {
648 if ( $mode == LIST_AND || $mode == LIST_SET ) {
649 $list .= $field.'=';
650 }
651 $list .= $this->addQuotes( $value );
652 }
653 }
654 return $list;
655 }
656
657 function selectDB( $db )
658 {
659 $this->mDBname = $db;
660 mysql_select_db( $db, $this->mConn );
661 }
662
663 function startTimer( $timeout )
664 {
665 global $IP;
666 if( function_exists( 'mysql_thread_id' ) ) {
667 # This will kill the query if it's still running after $timeout seconds.
668 $tid = mysql_thread_id( $this->mConn );
669 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
670 }
671 }
672
673 function stopTimer()
674 {
675 }
676
677 function tableName( $name ) {
678 global $wgSharedDB;
679 if ( $this->mTablePrefix !== '' ) {
680 if ( strpos( '.', $name ) === false ) {
681 $name = $this->mTablePrefix . $name;
682 }
683 }
684 if ( isset( $wgSharedDB ) && 'user' == $name ) {
685 $name = $wgSharedDB . '.' . $name;
686 }
687 return $name;
688 }
689
690 function tableNames() {
691 $inArray = func_get_args();
692 $retVal = array();
693 foreach ( $inArray as $name ) {
694 $retVal[$name] = $this->tableName( $name );
695 }
696 return $retVal;
697 }
698
699 function strencode( $s ) {
700 return addslashes( $s );
701 }
702
703 # If it's a string, adds quotes and backslashes
704 # Otherwise returns as-is
705 function addQuotes( $s ) {
706 if ( is_null( $s ) ) {
707 $s = 'NULL';
708 } else {
709 # This will also quote numeric values. This should be harmless,
710 # and protects against weird problems that occur when they really
711 # _are_ strings such as article titles and string->number->string
712 # conversion is not 1:1.
713 $s = "'" . $this->strencode( $s ) . "'";
714 }
715 return $s;
716 }
717
718 # Returns an appropriately quoted sequence value for inserting a new row.
719 # MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
720 # subclass will return an integer, and save the value for insertId()
721 function nextSequenceValue( $seqName ) {
722 return NULL;
723 }
724
725 # USE INDEX clause
726 # PostgreSQL doesn't have them and returns ""
727 function useIndexClause( $index ) {
728 return 'USE INDEX ('.$index.')';
729 }
730
731 # REPLACE query wrapper
732 # PostgreSQL simulates this with a DELETE followed by INSERT
733 # $row is the row to insert, an associative array
734 # $uniqueIndexes is an array of indexes. Each element may be either a
735 # field name or an array of field names
736 #
737 # It may be more efficient to leave off unique indexes which are unlikely to collide.
738 # However if you do this, you run the risk of encountering errors which wouldn't have
739 # occurred in MySQL
740 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
741 $table = $this->tableName( $table );
742
743 # Single row case
744 if ( !is_array( reset( $rows ) ) ) {
745 $rows = array( $rows );
746 }
747
748 $sql = "REPLACE INTO $table (" . implode( ',', array_flip( $rows[0] ) ) .') VALUES ';
749 $first = true;
750 foreach ( $rows as $row ) {
751 if ( $first ) {
752 $first = false;
753 } else {
754 $sql .= ',';
755 }
756 $sql .= '(' . $this->makeList( $row ) . ')';
757 }
758 return $this->query( $sql, $fname );
759 }
760
761 # DELETE where the condition is a join
762 # MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
763 #
764 # $delTable is the table to delete from
765 # $joinTable is the other table
766 # $delVar is the variable to join on, in the first table
767 # $joinVar is the variable to join on, in the second table
768 # $conds is a condition array of field names mapped to variables, ANDed together in the WHERE clause
769 #
770 # For safety, an empty $conds will not delete everything. If you want to delete all rows where the
771 # join condition matches, set $conds='*'
772 #
773 # DO NOT put the join condition in $conds
774 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
775 if ( !$conds ) {
776 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
777 }
778
779 $delTable = $this->tableName( $delTable );
780 $joinTable = $this->tableName( $joinTable );
781 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
782 if ( $conds != '*' ) {
783 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
784 }
785
786 return $this->query( $sql, $fname );
787 }
788
789 # Returns the size of a text field, or -1 for "unlimited"
790 function textFieldSize( $table, $field ) {
791 $table = $this->tableName( $table );
792 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
793 $res = $this->query( $sql, 'Database::textFieldSize' );
794 $row = $this->fetchObject( $res );
795 $this->freeResult( $res );
796
797 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
798 $size = $m[1];
799 } else {
800 $size = -1;
801 }
802 return $size;
803 }
804
805 function lowPriorityOption() {
806 return 'LOW_PRIORITY';
807 }
808
809 # Use $conds == "*" to delete all rows
810 function delete( $table, $conds, $fname = 'Database::delete' ) {
811 if ( !$conds ) {
812 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
813 }
814 $table = $this->tableName( $table );
815 $sql = "DELETE FROM $table ";
816 if ( $conds != '*' ) {
817 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
818 }
819 return $this->query( $sql, $fname );
820 }
821
822 # INSERT SELECT wrapper
823 # $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
824 # Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
825 # $conds may be "*" to copy the whole table
826 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
827 $destTable = $this->tableName( $destTable );
828 $srcTable = $this->tableName( $srcTable );
829 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
830 ' SELECT ' . implode( ',', $varMap ) .
831 " FROM $srcTable";
832 if ( $conds != '*' ) {
833 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
834 }
835 return $this->query( $sql, $fname );
836 }
837
838 function limitResult($limit,$offset) {
839 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
840 }
841
842 function wasDeadlock() {
843 return $this->lastErrno() == 1213;
844 }
845
846 function deadlockLoop() {
847 $myFname = 'Database::deadlockLoop';
848
849 $this->query( 'BEGIN', $myFname );
850 $args = func_get_args();
851 $function = array_shift( $args );
852 $oldIgnore = $dbw->ignoreErrors( true );
853 $tries = DEADLOCK_TRIES;
854 if ( is_array( $function ) ) {
855 $fname = $function[0];
856 } else {
857 $fname = $function;
858 }
859 do {
860 $retVal = call_user_func_array( $function, $args );
861 $error = $this->lastError();
862 $errno = $this->lastErrno();
863 $sql = $this->lastQuery();
864
865 if ( $errno ) {
866 if ( $dbw->wasDeadlock() ) {
867 # Retry
868 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
869 } else {
870 $dbw->reportQueryError( $error, $errno, $sql, $fname );
871 }
872 }
873 } while( $dbw->wasDeadlock && --$tries > 0 );
874 $this->ignoreErrors( $oldIgnore );
875 if ( $tries <= 0 ) {
876 $this->query( 'ROLLBACK', $myFname );
877 $this->reportQueryError( $error, $errno, $sql, $fname );
878 return false;
879 } else {
880 $this->query( 'COMMIT', $myFname );
881 return $retVal;
882 }
883 }
884
885 # Do a SELECT MASTER_POS_WAIT()
886 function masterPosWait( $file, $pos, $timeout ) {
887 $encFile = $this->strencode( $file );
888 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
889 $res = $this->query( $sql, 'Database::masterPosWait' );
890 if ( $res && $row = $this->fetchRow( $res ) ) {
891 $this->freeResult( $res );
892 return $row[0];
893 } else {
894 return false;
895 }
896 }
897
898 # Get the position of the master from SHOW SLAVE STATUS
899 function getSlavePos() {
900 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
901 $row = $this->fetchObject( $res );
902 if ( $row ) {
903 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
904 } else {
905 return array( false, false );
906 }
907 }
908
909 # Get the position of the master from SHOW MASTER STATUS
910 function getMasterPos() {
911 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
912 $row = $this->fetchObject( $res );
913 if ( $row ) {
914 return array( $row->File, $row->Position );
915 } else {
916 return array( false, false );
917 }
918 }
919
920 # Begin a transaction, or if a transaction has already started, continue it
921 function begin( $fname = 'Database::begin' ) {
922 if ( !$this->mTrxLevel ) {
923 $this->immediateBegin( $fname );
924 } else {
925 $this->mTrxLevel++;
926 }
927 }
928
929 # End a transaction, or decrement the nest level if transactions are nested
930 function commit( $fname = 'Database::commit' ) {
931 if ( $this->mTrxLevel ) {
932 $this->mTrxLevel--;
933 }
934 if ( !$this->mTrxLevel ) {
935 $this->immediateCommit( $fname );
936 }
937 }
938
939 # Rollback a transaction
940 function rollback( $fname = 'Database::rollback' ) {
941 $this->query( 'ROLLBACK', $fname );
942 $this->mTrxLevel = 0;
943 }
944
945 # Begin a transaction, committing any previously open transaction
946 function immediateBegin( $fname = 'Database::immediateBegin' ) {
947 $this->query( 'BEGIN', $fname );
948 $this->mTrxLevel = 1;
949 }
950
951 # Commit transaction, if one is open
952 function immediateCommit( $fname = 'Database::immediateCommit' ) {
953 $this->query( 'COMMIT', $fname );
954 $this->mTrxLevel = 0;
955 }
956
957 # Return MW-style timestamp used for MySQL schema
958 function timestamp( $ts=0 ) {
959 return wfTimestamp(TS_MW,$ts);
960 }
961
962 function &resultObject( &$result ) {
963 if( empty( $result ) ) {
964 return NULL;
965 } else {
966 return new ResultWrapper( $this, $result );
967 }
968 }
969 }
970
971 /**
972 * Database abstraction object for mySQL
973 * @category database
974 */
975 class DatabaseMysql extends Database {
976 # Inherit all
977 }
978
979
980 /**
981 * Result wrapper for grabbing data queried by someone else
982 * @category database
983 */
984 class ResultWrapper {
985 var $db, $result;
986
987 function ResultWrapper( $database, $result ) {
988 $this->db =& $database;
989 $this->result =& $result;
990 }
991
992 function numRows() {
993 return $this->db->numRows( $this->result );
994 }
995
996 function &fetchObject() {
997 return $this->db->fetchObject( $this->result );
998 }
999
1000 function &fetchRow() {
1001 return $this->db->fetchRow( $this->result );
1002 }
1003
1004 function free() {
1005 $this->db->freeResult( $this->result );
1006 unset( $this->result );
1007 unset( $this->db );
1008 }
1009 }
1010
1011 #------------------------------------------------------------------------------
1012 # Global functions
1013 #------------------------------------------------------------------------------
1014
1015 /**
1016 * Standard fail function, called by default when a connection cannot be
1017 * established.
1018 * Displays the file cache if possible
1019 */
1020 function wfEmergencyAbort( &$conn, $error ) {
1021 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1022
1023 if( !headers_sent() ) {
1024 header( 'HTTP/1.0 500 Internal Server Error' );
1025 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1026 /* Don't cache error pages! They cause no end of trouble... */
1027 header( 'Cache-control: none' );
1028 header( 'Pragma: nocache' );
1029 }
1030 $msg = $wgSiteNotice;
1031 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1032 $text = $msg;
1033
1034 if($wgUseFileCache) {
1035 if($wgTitle) {
1036 $t =& $wgTitle;
1037 } else {
1038 if($title) {
1039 $t = Title::newFromURL( $title );
1040 } elseif (@/**/$_REQUEST['search']) {
1041 $search = $_REQUEST['search'];
1042 echo wfMsgNoDB( 'searchdisabled' );
1043 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1044 wfErrorExit();
1045 } else {
1046 $t = Title::newFromText( wfMsgNoDB( 'mainpage' ) );
1047 }
1048 }
1049
1050 $cache = new CacheManager( $t );
1051 if( $cache->isFileCached() ) {
1052 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1053 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1054
1055 $tag = '<div id="article">';
1056 $text = str_replace(
1057 $tag,
1058 $tag . $msg,
1059 $cache->fetchPageText() );
1060 }
1061 }
1062
1063 echo $text;
1064 wfErrorExit();
1065 }
1066
1067 ?>